<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise.allSettled()</title>
</head>
<body>
    <h1>Promise.allSettled()</h1>
    <h2>等到所有Promise都已经fulfilled或rejected后，才会返回结果</h2>

    <script>
        // 基本用法
        const promises = [
            Promise.resolve(33),
            new Promise(resolve => setTimeout(() => resolve(66), 0)),
            Promise.reject(new Error('出错了')),
            Promise.resolve(99)
        ];

        Promise.allSettled(promises)
            .then(results => {
                console.log(results);
                // [
                //   { status: "fulfilled", value: 33 },
                //   { status: "fulfilled", value: 66 },
                //   { status: "rejected", reason: Error: 出错了 },
                //   { status: "fulfilled", value: 99 }
                // ]
            });

        // 实际应用：批量获取用户数据
        function getUserData(id) {
            return new Promise((resolve, reject) => {
                if (id % 2 === 0) {
                    resolve({ id, name: `用户${id}` });
                } else {
                    reject(new Error(`获取用户${id}数据失败`));
                }
            });
        }

        const userIds = [1, 2, 3, 4, 5];
        Promise.allSettled(userIds.map(id => getUserData(id)))
            .then(results => {
                const successful = results.filter(r => r.status === 'fulfilled');
                const failed = results.filter(r => r.status === 'rejected');
                
                console.log('成功获取的用户:', successful.map(s => s.value));
                console.log('获取失败的数量:', failed.length);
            });
    </script>
</body>
</html> 